package com.isyscore.os.etl.controller;

import com.isyscore.device.common.model.RespDTO;
import com.isyscore.os.core.exception.DataFactoryException;
import com.isyscore.os.core.exception.ErrorCode;
import com.isyscore.os.core.model.entity.JobConfig;
import com.isyscore.os.etl.constant.CommonConstant;
import com.isyscore.os.etl.model.dto.DataSourceDTO;
import com.isyscore.os.etl.model.enums.JobType;
import com.isyscore.os.etl.model.form.SQLParam;
import com.isyscore.os.etl.service.impl.JobConfigServiceImpl;
import com.isyscore.os.etl.utils.SqlValidationUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.Statement;
import java.util.List;
import java.util.Objects;

@Api("预校验")
@RestController
@RequestMapping("${api-full-prefix}/validate")
@Slf4j
@RequiredArgsConstructor
public class ValidationController {

    private final JobConfigServiceImpl jobConfigService;

    @PostMapping("/sql")
    public RespDTO<Void> validateSql(@RequestBody SQLParam sqlParam) {
        if (StringUtils.isEmpty(sqlParam.getFlinkSql())) {
            throw new DataFactoryException(ErrorCode.MISSING_PARAMS, "flinkSql");
        }
        List<String> listSql = SqlValidationUtils.toSqlList(sqlParam.getFlinkSql());
        if (CollectionUtils.isEmpty(listSql)) {
            log.error("没有检测到有效sql语句，请检查是否缺少分号分隔符");
            throw new DataFactoryException(ErrorCode.PARAM_ERROR);
        }
        SqlValidationUtils.preCheckSql(listSql);
        return RespDTO.onSuc();
    }

    @PostMapping("/rowsql")
    public RespDTO<Void> validateRowSql(@RequestBody JobConfig jobConfig) {
        if (StringUtils.isEmpty(jobConfig.getRowSql())) {
            throw new DataFactoryException(ErrorCode.MISSING_PARAMS, "sql 文本");
        }
        String err = jobConfigService.preCheckSQL(jobConfig);
        if (Objects.equals(jobConfig.getIsChecked(), CommonConstant.TRUE)) {
            return RespDTO.onSuc();
        } else {
            return RespDTO.onFail(ErrorCode.PRECHECK_ERROR.getCode(), err);
        }
    }
}
